package com.dangf.launcher.server.pulgin.soft

import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.support.v7.app.AlertDialog
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.dangf.launcher.server.R
import com.dangf.launcher.server.app.V
import com.zxy.tiny.Tiny
import org.litepal.crud.DataSupport
import pw.hais.utils_lib.app.BasePopupWindow
import pw.hais.utils_lib.utils.L
import pw.hais.utils_lib.utils.ShellUtils


/**
 * Created by hais1992 on 2017/9/29.
 */
class SoftEditWindows(val fragment: SoftManageFragment) : BasePopupWindow(fragment.activity, R.layout.soft_manage_edit_windows) {
    private var text_delete: TextView? = null
    private var image_icon: ImageView? = null
    private var text_lable: TextView? = null
    private var text_name: TextView? = null
    private var text_version: TextView? = null
    private var text_package: TextView? = null
    private var btn_ok: Button? = null
    private var text_close: TextView? = null
    private var checkbox_status: CheckBox? = null
    private var checkbox_admin: CheckBox? = null
    private var item: Soft? = null

    override fun initView(v: View) {
        text_delete = v.findViewById(R.id.text_delete)
        image_icon = v.findViewById(R.id.image_icon)
        text_lable = v.findViewById(R.id.text_lable)
        text_name = v.findViewById(R.id.text_name)
        text_version = v.findViewById(R.id.text_version)
        text_package = v.findViewById(R.id.text_package)
        checkbox_status = v.findViewById(R.id.checkbox_status)
        checkbox_admin = v.findViewById(R.id.checkbox_admin)

        text_close = v.findViewById(R.id.text_close)
        text_close?.setOnClickListener { dismiss() }
        btn_ok = v.findViewById(R.id.btn_ok)
        btn_ok?.setOnClickListener { saveSoftAndZipImages() }
        text_delete?.setOnClickListener {
            AlertDialog.Builder(activity).setTitle("删除").setMessage("您是否要删除此条记录？删除后将无法恢复").setPositiveButton("删除") { _, _ ->
                item?.delete()
                L.showShort("数据已删除")
                dismiss()
                fragment.onRefreshData()
            }.setNegativeButton("取消", null).show()
        }
    }

    fun showContent(item: Soft, icon: Drawable? = null) {
        this.item = item
        val data = DataSupport.where(" packageName = '${item.packageName}'").find(Soft::class.java)
        if (icon != null && !data.isEmpty()) {
            this.item = data.last()
            text_lable?.text = "软件升级"
            text_delete?.visibility = View.GONE
            image_icon?.setImageDrawable(icon)
        } else if (icon == null && !data.isEmpty()) {
            this.item = data.last()
            text_lable?.text = "软件编辑"
            text_delete?.visibility = View.VISIBLE
            Glide.with(activity).load("http://${V.HTTP_SERVER_IP}:${V.HTTP_SERVER_PORT}/${item.icon}").into(image_icon)
        } else {
            text_lable?.text = "发布软件"
            text_delete?.visibility = View.GONE
            image_icon?.setImageDrawable(icon)
        }
        showSoftInfo()
        showContent()
    }

    private fun showSoftInfo() {
        checkbox_admin!!.isChecked = item!!.type == "管理工具"
        checkbox_status!!.isChecked = item!!.status == "启用"
        text_name?.text = "名称：${item?.name}"
        text_version?.text = "版本：${item?.version}"
        text_package?.text = "包名：${item?.packageName}"
    }

    //压缩图片
    fun saveSoftAndZipImages() {
        Tiny.getInstance().source((image_icon!!.drawable as BitmapDrawable).bitmap).asFile().compress { isSuccess, outfile ->
            L.e("图片处理结果：$isSuccess,$outfile")
            ShellUtils.execCmd("cp -rf ${item?.apkUrl} ${V.SOFT_DATA_PATH}/${item?.packageName}.apk && mv -f $outfile ${V.SOFT_DATA_PATH}/${item?.packageName}.png", false)
            item!!.icon = "file?name=" + item?.packageName + ".png"
            item!!.apkUrl = "file?name=" + item?.packageName + ".apk"
            item!!.type = if (checkbox_admin!!.isChecked) "管理工具" else "用户软件"
            item!!.status = if (checkbox_status!!.isChecked) "启用" else "禁用"
            val saveStatus = item!!.isSaved
            if (item!!.save()) {
                if (saveStatus) L.showShort("修改成功！") else L.showShort("发布成功！")
                dismiss()
                fragment.onRefreshData()
            } else {
                L.showShort("软件保存失败，请检查是否已有相同软件！")
            }
        }
    }


}